package com.moxiao.yfjh.module.blind.controller.admin.sessionRecord;

import com.alibaba.fastjson.JSONObject;
import com.moxiao.yfjh.framework.common.pojo.CommonResult;
import com.moxiao.yfjh.framework.common.pojo.PageResult;
import com.moxiao.yfjh.framework.excel.core.util.ExcelUtils;
import com.moxiao.yfjh.framework.operatelog.core.annotations.OperateLog;
import com.moxiao.yfjh.module.blind.common.GenNoCommonMethod;
import com.moxiao.yfjh.module.blind.controller.admin.memberMessage.vo.MemberMessageExportReqVO;
import com.moxiao.yfjh.module.blind.controller.admin.memberMessage.vo.MemberMessagePageReqVO;
import com.moxiao.yfjh.module.blind.controller.admin.memberMessage.vo.MemberMessageRespVO;
import com.moxiao.yfjh.module.blind.controller.admin.sessionRecord.vo.*;
import com.moxiao.yfjh.module.blind.convert.memberMessage.MemberMessageConvert;
import com.moxiao.yfjh.module.blind.convert.sessionRecord.SessionRecordConvert;
import com.moxiao.yfjh.module.blind.dal.dataobject.member.BlindMemberUserDO;
import com.moxiao.yfjh.module.blind.dal.dataobject.memberMessage.MemberMessageDO;
import com.moxiao.yfjh.module.blind.dal.dataobject.sessionRecord.SessionRecordDO;
import com.moxiao.yfjh.module.blind.service.member.BlindMemberUserService;
import com.moxiao.yfjh.module.blind.service.memberMessage.MemberMessageService;
import com.moxiao.yfjh.module.blind.service.sessionRecord.SessionRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import static com.moxiao.yfjh.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.moxiao.yfjh.framework.common.pojo.CommonResult.success;
import static com.moxiao.yfjh.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static com.moxiao.yfjh.module.blind.common.ErrorCodeConstants.SESSION_RECORD_CREATE_FOUNDER;
import static com.moxiao.yfjh.module.blind.common.ErrorCodeConstants.SESSION_RECORD_CREATE_PARTICIPANTS;


@Tag(name = "管理后台 - 相亲会话记录")
@RestController
@RequestMapping("/blind/session-record")
@Validated
public class SessionRecordController {

    @Resource
    private SessionRecordService sessionRecordService;
    @Resource
    private GenNoCommonMethod genNoCommonMethod;

    @Resource
    private MemberMessageService memberMessageService;

    @Resource
    private BlindMemberUserService memberUserService;

    @PostMapping("/create")
    @Operation(summary = "创建相亲会话记录")
    @PreAuthorize("@ss.hasPermission('blind:session-record:create')")
    public CommonResult<JSONObject> createSessionRecord(@Valid @RequestBody SessionRecordCreateReqVO createReqVO) {

        if (StringUtils.isEmpty(createReqVO.getFounder()) || "undefined".equals(createReqVO.getFounder())) {
            throw exception(SESSION_RECORD_CREATE_FOUNDER);
        }

        if (StringUtils.isEmpty(createReqVO.getParticipants()) || "undefined".equals(createReqVO.getParticipants())) {
            throw exception(SESSION_RECORD_CREATE_PARTICIPANTS);
        }

        createReqVO.setConversationId(createReqVO.getConversationID());
        JSONObject jsonObject = new JSONObject();

//        判断会话是否已经创建过
        List<SessionRecordDO> sessionRecordList = sessionRecordService.getSessionRecordList(new SessionRecordExportReqVO().setFounder(createReqVO.getFounder()).setParticipants(createReqVO.getParticipants()));
        if (CollectionUtils.isNotEmpty(sessionRecordList)) {
//            不创建会话
            jsonObject.put("userId", sessionRecordList.get(0).getFounder());
            jsonObject.put("recordID", sessionRecordList.get(0).getRecordId());
            return success(jsonObject);
        }

        List<SessionRecordDO> sessionRecordList1 = sessionRecordService.getSessionRecordList(new SessionRecordExportReqVO().setParticipants(createReqVO.getFounder()).setFounder(createReqVO.getParticipants()));
        if (CollectionUtils.isNotEmpty(sessionRecordList1)) {
//            不创建会话
            jsonObject.put("userId", sessionRecordList1.get(0).getFounder());
            jsonObject.put("recordID", sessionRecordList1.get(0).getRecordId());
            return success(jsonObject);
        }
//        没有，则创建
        genNoCommonMethod.addSessionNo(createReqVO);
        Long sessionRecord = sessionRecordService.createSessionRecord(createReqVO);
        //        todo 生成会话id
        String recordID = generateRecordId(sessionRecord, createReqVO);
        jsonObject.put("userId", createReqVO.getFounder());
        jsonObject.put("recordID", recordID);
        jsonObject.put("id", sessionRecord);
        return success(jsonObject);
    }


    @PutMapping("/update")
    @Operation(summary = "更新相亲会话记录")
    @PreAuthorize("@ss.hasPermission('blind:session-record:update')")
    public CommonResult<Boolean> updateSessionRecord(@Valid @RequestBody SessionRecordUpdateReqVO updateReqVO) {
        sessionRecordService.updateSessionRecord(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除相亲会话记录")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('blind:session-record:delete')")
    public CommonResult<Boolean> deleteSessionRecord(@RequestParam("id") Long id) {
        sessionRecordService.deleteSessionRecord(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得相亲会话记录")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('blind:session-record:query')")
    public CommonResult<SessionRecordRespVO> getSessionRecord(@RequestParam("id") Long id) {
        SessionRecordDO sessionRecord = sessionRecordService.getSessionRecord(id);
        return success(SessionRecordConvert.INSTANCE.convert(sessionRecord));
    }

    @GetMapping("/list")
    @Operation(summary = "获得相亲会话记录列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('blind:session-record:query')")
    public CommonResult<List<SessionRecordRespVO>> getSessionRecordList(@RequestParam("ids") Collection<Long> ids) {
        List<SessionRecordDO> list = sessionRecordService.getSessionRecordList(ids);
        return success(SessionRecordConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @Operation(summary = "获得相亲会话记录分页")
//    @PreAuthorize("@ss.hasPermission('blind:session-record:query')")
    public CommonResult<?> getSessionRecordPage(@Valid SessionRecordPageReqVO pageVO) {
        PageResult<SessionRecordDO> pageResult = sessionRecordService.getSessionRecordPageByUserId(pageVO);
        PageResult<SessionRecordRespVO> sessionRecordRespVOPageResult = SessionRecordConvert.INSTANCE.convertPage(pageResult);
        if (Objects.nonNull(sessionRecordRespVOPageResult)) {
            if (CollectionUtils.isNotEmpty(sessionRecordRespVOPageResult.getList())) {
                sessionRecordRespVOPageResult.getList().forEach(sessionRecordDO ->{
                    MemberMessageDO memberMessagePageByUserId = memberMessageService.getMemberMessagePageByUserId(new MemberMessagePageReqVO().setRecordId(sessionRecordDO.getRecordId()));
                    if (memberMessagePageByUserId != null) {
                        sessionRecordDO.setContent(memberMessagePageByUserId.getMessageContent());
                        sessionRecordDO.setCreateTime(memberMessagePageByUserId.getCreateTime());
                    }
                    if (Objects.equals(sessionRecordDO.getParticipants(),String.valueOf(pageVO.getUserId()))) {
                        BlindMemberUserDO memberUser = memberUserService.getMemberUser(Long.valueOf(sessionRecordDO.getParticipants()));
                        if (Objects.nonNull(memberUser)){
                            sessionRecordDO.setChatObject(memberUser.getNickname());
                            sessionRecordDO.setChatObjectMobile(memberUser.getMobile());
                            sessionRecordDO.setParticipantsName(memberUser.getNickname());
                        }
                    } else {
                        BlindMemberUserDO memberUser = memberUserService.getMemberUser(Long.valueOf(sessionRecordDO.getFounder()));
                        if (Objects.nonNull(memberUser)) {
                            sessionRecordDO.setChatObject(memberUser.getNickname());
                            sessionRecordDO.setChatObjectMobile(memberUser.getMobile());
                            sessionRecordDO.setFounderName(memberUser.getNickname());
                        }
                    }
                    if (StringUtils.isEmpty(sessionRecordDO.getFounderName())){
                        BlindMemberUserDO memberUser = memberUserService.getMemberUser(Long.valueOf(sessionRecordDO.getFounder()));
                        if (Objects.nonNull(memberUser)) {
                            sessionRecordDO.setFounderName(memberUser.getNickname());
                        }
                    }
                    if (StringUtils.isEmpty(sessionRecordDO.getParticipantsName())){
                        BlindMemberUserDO memberUser = memberUserService.getMemberUser(Long.valueOf(sessionRecordDO.getParticipants()));
                        if (Objects.nonNull(memberUser)) {
                            sessionRecordDO.setParticipantsName(memberUser.getNickname());
                        }
                    }
                    sessionRecordDO.setConversationID(sessionRecordDO.getConversationId());

                });
                Collections.sort(pageResult.getList(),(a,b) -> b.getCreateTime().compareTo(a.getCreateTime()));
            }
        }
        return success(sessionRecordRespVOPageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出相亲会话记录 Excel")
    @PreAuthorize("@ss.hasPermission('blind:session-record:export')")
    @OperateLog(type = EXPORT)
    public void exportSessionRecordExcel(@Valid SessionRecordExportReqVO exportReqVO,
                                         HttpServletResponse response) throws IOException {
        List<SessionRecordDO> list = sessionRecordService.getSessionRecordList(exportReqVO);
        // 导出 Excel
        List<SessionRecordExcelVO> datas = SessionRecordConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "相亲会话记录.xls", "数据", SessionRecordExcelVO.class, datas);
    }

    @GetMapping("/listByRecordId")
    @Operation(summary = "通过会话ID获得相亲聊天记录列表")
    @Parameter(name = "recordId", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('blind:member-message:listByRecordId')")
    public CommonResult<List<MemberMessageRespVO>> getMemberMessageList(@RequestParam("recordId") String recordId) {
        List<MemberMessageDO> list = memberMessageService.getMemberMessageList(new MemberMessageExportReqVO().setRecordId(recordId));
        list.stream().sorted((a, b) -> b.getCreateTime().compareTo(a.getCreateTime()));
        return success(MemberMessageConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/messagePage")
    @Operation(summary = "获得相亲聊天记录分页")
    @PreAuthorize("@ss.hasPermission('blind:member-message:query')")
    public CommonResult<PageResult<MemberMessageRespVO>> getMemberMessagePage(@Valid MemberMessagePageReqVO pageVO) {
        PageResult<MemberMessageDO> pageResult = memberMessageService.getMemberMessagePage(pageVO);
        return success(MemberMessageConvert.INSTANCE.convertPage(pageResult));
    }

    public String generateRecordId(Long sessionRecordId, SessionRecordCreateReqVO createReqVO) {
        StringBuilder recordId = new StringBuilder();
        long timestamp = System.currentTimeMillis();
        recordId.append(timestamp);
        recordId.append(createReqVO.getFounder());
        recordId.append(createReqVO.getParticipants());
        recordId.append(sessionRecordId);
        SessionRecordUpdateReqVO updateReqVO = new SessionRecordUpdateReqVO();
        updateReqVO.setId(sessionRecordId);
        updateReqVO.setRecordId(recordId.toString());
        sessionRecordService.updateSessionRecord(updateReqVO);
        return recordId.toString();
    }

}
